<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Container\ContainerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Utils\JwtToken;

class AdminMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response)
    {
        $this->container = $container;
        $this->response = $response;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $token = $request->getHeader('Authorization');
            if (empty($token) && count($token) <= 0) {
                throw new \Exception('empty token');
            }
            $data = JwtToken::decode($token[0], 'admin-key');
            $request = $request->withHeader('admin_user_id', $data['data']['id']);
        }catch(\Exception $e) {
            return $this->response->json([
                'code' => 10001,
                'msg' => '登录校验失败'
            ]);
        }

        return $handler->handle($request);
    }
}